package Utils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import Gui.TestGui;

/**
 * should contain things like a parser, ascii characters decoder etc.
 * @author ale
 *
 */
public class ResultDisplayUtility {

	/**
	 * Parse XML tstmt files, e.g. write title for <chapter><chaptertitle> ...
	 * @param text
	 * @return
	 */
	public String parseTstmtStructure(String text) {
		String result = "";
		String[] corrected = {"</?\\w++[^>]*+>"};
		for (int i = 0; i < corrected.length; i++) {
			result = text.replaceAll(corrected[i], "");
		}
		return result;	
	}

	/**
	 * Substitutes special ascii encoded characters into their form
	 * @param text
	 * @return
	 */
	public String decodeSpecialChars(String text) {
		String out = text;
		//TODO
		text = text.replaceAll("<.*>", "?"); //for now remove tags
		return text;
	}

	/**
	 *  Returns the test into RTF format
	 */
	public String transformToRTF(String text) {
		//header:
		text = "{\\rtf1\\ansi\\ansicpg1252\\cocoartf949\\cocoasubrtf330\n{\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\paperw11900\\paperh16840\\margl1440\\margr1440\\vieww9000\\viewh8400\\viewkind0\n\\pard\\tx566\\tx1133\\tx1700\\tx2267\\tx2834\\tx3401\\tx3968\\tx4535\\tx5102\\tx5669\\tx6\n\n236\\tx6803\\ql\\qnatural\\pardirnatural\\f0\\fs24 \\cf0"
			+ text		
			+ "}";
		text = text.replaceAll("\n", "\\\n");
		return text;	
	}


	/**
	 * Returns all the contents of a file that the user desire to display its whole version
	 * @param fileName
	 * @return
	 */
	public String readFromFile(String fileName, TestGui gui) {
		String text = null;
		int lines = 0;
		BufferedReader reader = null;
		StringBuffer fileContents = new StringBuffer();
		File file = new File(fileName);
		try {
			reader = new BufferedReader(new FileReader(file));
			while ((text = reader.readLine()) != null) {
				fileContents.append(text).append(System.getProperty("line.separator"));
				lines++;
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//gui.setStatus("ciao");
		gui.setStatus("Opened " + fileName + ", " + lines + " lines");
		return fileContents.toString();
	}


//	public static void main(String[] args) {
//	ResultDisplayUtility res = new ResultDisplayUtility();
//	String test = "<bella>denedjedj</bella>";
//	String result = res.parseTstmtStructure(test);
//	System.out.println(result);

//	TestGui gui = new TestGui();
//	res.getPartOfText("rel200/nt/nt.xml", 50, 70, gui, 10, 10);  // 40 - 60
//	res.getPartOfText("rel200/nt/nt.xml", 50, 70, gui, 60, 100); // 0  - 70


//	}

	/**
	 * This is responsible of displaying X verses before and Y verses after
	 */
	public String getPartOfText(String fileName, int bookId, int desired, int max_in_collection, TestGui gui, int resBefore, int resAfter) {
		String allVersesString = "";
		ArrayList<Node> allVerses = new ArrayList<Node>(); //note that this is different from allVerses in the index parser
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder;
		Document doc = null;
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			doc = docBuilder.parse (new File(fileName)); 		//
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// normalize text representation
		doc.getDocumentElement ().normalize ();
		Element tstmt = doc.getDocumentElement(); //ROOT

		//titles:
		Element coverpg = (Element) tstmt.getElementsByTagName("coverpg").item(0);
		String coverpgtitle = coverpg.getElementsByTagName("title").item(0).getTextContent();

		NodeList bookcoll = tstmt.getElementsByTagName("bookcoll");
		if (bookcoll.getLength() == 0) {
			bookcoll = tstmt.getElementsByTagName("suracoll");
		}
		Element firstBookcoll = (Element)bookcoll.item(0);
		NodeList books = firstBookcoll.getElementsByTagName("book"); //book or sura
		if (books.getLength() == 0) {
			books = firstBookcoll.getElementsByTagName("sura");
		}
		// get book: bookId
		Element currentBook = (Element)books.item(bookId);
		Element bktlong = (Element)currentBook.getElementsByTagName("bktlong").item(0);
		String firstBktLongString = bktlong.getTextContent();
		//bktShort
		Element bktshort = (Element)currentBook.getElementsByTagName("bktshort").item(0);
		String firstBktShortString = bktshort.getTextContent();	
		//epigraph:
		NodeList epigraphs = currentBook.getElementsByTagName("epigraph");
		if (epigraphs.getLength() != 0) {
			allVerses.add(epigraphs.item(0));
			desired++;
		}
		NodeList verses = currentBook.getElementsByTagName("v");
		for (int j = 0; j < verses.getLength(); j++) {		
			allVerses.add(verses.item(j));
		}


		//results to display: range
		int begin = (desired - resBefore < 0 ? 0 : desired - resBefore);
		int end = (resAfter+desired > max_in_collection ? max_in_collection : resAfter+desired);

		//write html

		//book info:
		allVersesString += "<h2>" + coverpgtitle+ "</h2>";
		allVersesString += "<h3>" + firstBktShortString + "</h3>";
		allVersesString += "<h4>" + firstBktLongString + "</h4>";


		allVersesString += "<table>\n" ;
		allVersesString += "<tr><td width=\"30\"><font size=\"-1\">v.#</font></td><td><font =\"-1\">verse</font></td></tr>";
		String formatterTag = "";
		String endFormatterTag = "</font>";
		for (int i = begin ; i < end ; i++) { //98 : removed -1
			if (i == desired)
				formatterTag = "<font color='blue'>";
			else formatterTag = "<font>";

			Node verse = allVerses.get(i);
			allVersesString += "<tr><td valign=\"top\">"+ i + "</td><td>" + formatterTag + verse.getTextContent() + endFormatterTag + " </td></tr>\n";
			//allVersesString += verse.getTextContent() + "<hr>";
		}
		allVersesString += "</table>";

		System.out.println("VERSES IN RANGE: " + begin + " AND " + end);
		return allVersesString;
	}


//	public String getPartOfText2(String fileName, int desired, int max_in_collection, TestGui gui, int resBefore, int resAfter) {
//	String verseTag = "<v>";
//	String verseCloseTag= "</v>";
//	String partOfText = "";
//	String wholeText = readFromFile(fileName, gui);
//	int begin = (desired - resBefore < 0 ? 0 : desired - resBefore);
//	int after = (resAfter+desired > max_in_collection ? max_in_collection : resAfter+desired);
//	int howMany = after-begin;
//	int[] indeces = new int[howMany];
//	int lastVerseEndIndex = 0;
//	for (int i = 0 ; i < howMany ; i++) {
//	//EPIGRAPH??? 

//	int lastIndex;
//	if (i == 0)
//	lastIndex = 0;
//	else  lastIndex = indeces[i-1];
//	int index = wholeText.indexOf(verseTag, lastIndex+verseTag.length()); //lastIndex means search from there on, it's the last index (characters) where a <v> was found
//	indeces[i] = index;		
//	if(i == howMany-1) {
//	lastVerseEndIndex = wholeText.indexOf(verseCloseTag, index+verseTag.length());
//	System.out.println("Last begin verse: " + index);
//	System.out.println("Last verse index: " + lastVerseEndIndex);
//	}
//	}
//	System.out.println("End build indeces");
//	for (int i = 0 ; i < howMany ; i++) {
//	//System.out.println(indeces[i]);
//	int endIndex;
//	if(i == indeces.length-1)
//	endIndex = lastVerseEndIndex;//wholeText.length();
//	else endIndex = indeces[i+1]-verseTag.length()-verseCloseTag.length();//indeces[i+1]; 
//	System.out.println(i);
//	String v = wholeText.substring(indeces[i]+verseTag.length(), endIndex);	
//	partOfText += v;
//	}
//	//set gui buttons (prev? next?)
//	return partOfText;
//	}

}
